import axios from 'axios';
import qs from 'qs';
import { Message } from 'element-ui';
import { getUserToken, getLocalToken, getLocalTokentype, getUserInfo, getCookieTenant, getCurrentOU, getCompetitionToken } from '@/lib/auth'; // get token from cookie
import { getLocale } from '@/lib/lang';
import { judgeToLogout } from '@/lib/oidc_fun';
import { clearOut } from '@/lib/store/modules/user';

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 600000, // request timeout
  paramsSerializer: (params) => {
    return qs.stringify(params);
  }
});

// request interceptor
service.interceptors.request.use(
  async (config) => {
    // do something before request is sent
    const token = getLocalToken() || await getUserToken();
    config.headers['Accept-Language'] = getLocale() === 'en' ? 'en' : 'zh-Hans';
    if (token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = (getLocalTokentype() ? getLocalTokentype() : 'Bearer') + ' ' + token;
      if (config.method === 'post') {
        config.headers['content-type'] = 'application/json';
      }
    }
    config.headers['__tenant'] = getCookieTenant() ? getCookieTenant() : process.env.VUE_APP_Get_TenantId;
    config.headers['CURRENT_OU'] = getCurrentOU() || '';
    config.headers['COMPETITIONTOKEN'] = getCompetitionToken() || '';
    return config;
  },
  error => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data;
    return res;
  },
  error => {
    console.error(error.response); // for debug
    const response = error.response;
    const code = response.status;
    switch (code) {
      case 401:
        console.log('未授权');
        gouLogout();
        // clearOut();
        // mgr.signoutRedirect({ // 退出登陆
        //   extraQueryParams: {
        //     returnUrl: window.location.href
        //   }
        // }); // 跳转登陆
        break;
      case 403:
        error403(error);
        return Promise.reject(response.data);
      // break;
      default:
        return Promise.reject(response.data);
    }
  }
);

function error403 (error) {
  const response = error.response;
  if (!response.data) {
    const errorMsg = `${response.data && response.data.error && response.data.error.message ? response.data.error.message : '无权限'}`;
    Message({
      dangerouslyUseHTMLString: true,
      message: errorMsg,
      showClose: true,
      type: 'error',
      duration: 15 * 1000
    });
  }
}

function gouLogout () {
  const token = getLocalToken();
  if (!token) {
    return false;
  }
  const info = getUserInfo();
  const tenantId = info && info.tenantId ? info.tenantId : '';
  // this.goLogin();
  let href = window.location.href;
  href =
    href.indexOf('#') > -1
      ? href.indexOf('?') > -1
        ? href + '&'
        : href + '?'
      : href + '#/?';
  href = href.replace(/tenantid=[0-9a-z-]+|tenantid=/g, '').replace(/&&+/g, '&').replace('?&', '?');
  clearOut();
  judgeToLogout(href + 'tenantid=' + tenantId);
}

const request = (config) => {
  return new Promise((resolve, reject) => {
    const _config = JSON.parse(JSON.stringify(config));
    if (_config.method === 'get' && _config.params && typeof _config.params === 'object') {
      const _datas = {};
      for (const i in _config.params) {
        if (_config.params[i] !== null) {
          _datas[i] = _config.params[i];
        }
      }
      _config.params = _datas;
    }
    service.request(_config).then(res => {
      resolve(res);
    }, error => {
      reject(error);
    });
  });
};

export default request;
